package com.atguigu.spzx.user.service.Impl;

import com.atguigu.spzx.model.entity.order.Region;
import com.atguigu.spzx.model.entity.order.UserAddress;
import com.atguigu.spzx.user.mapper.UserAddressMapper;
import com.atguigu.spzx.user.service.RegionService;
import com.atguigu.spzx.user.service.UserAddressService;
import com.atguigu.spzx.util.AuthContextUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author LT
 * @create 2024-03-29-20:42
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements UserAddressService {

    @Resource
    private UserAddressMapper userAddressMapper;

    @Resource
    private RegionService regionService;

    @Override
    public List<UserAddress> findUserAddressList() {
        Long userId = AuthContextUtil.get1().getId();
        List<UserAddress> userAddressList = userAddressMapper.selectList(Wrappers.lambdaQuery(UserAddress.class)
                .eq(UserAddress::getUserId, userId));
        return userAddressList;
    }

    @Override
    public UserAddress getUserAddress(Long id) {
        UserAddress userAddress = userAddressMapper.selectById(id);
        return userAddress;
    }

    @Override
    public void saveUserAddress(UserAddress userAddress) {
        if (userAddress.getIsDefault().intValue() ==1){
            this.update(Wrappers.lambdaUpdate(UserAddress.class)
                    .set(UserAddress::getIsDefault , 0)
                    .eq(UserAddress::getUserId, AuthContextUtil.get1().getId())
                    .eq(UserAddress::getIsDefault,1));
        }
        Long userId = AuthContextUtil.get1().getId();
        userAddress.setUserId(userId);
        String provinceCode = userAddress.getProvinceCode();
        String cityCode = userAddress.getCityCode();
        String districtCode = userAddress.getDistrictCode();
        Region provinceRegion = regionService.getOne(Wrappers.lambdaQuery(Region.class)
                .eq(Region::getCode, provinceCode));
        Region cityRegion = regionService.getOne(Wrappers.lambdaQuery(Region.class)
                .eq(Region::getCode, cityCode));
        Region districtRegion = regionService.getOne(Wrappers.lambdaQuery(Region.class)
                .eq(Region::getCode, districtCode));

        String address = userAddress.getAddress();
        userAddress.setFullAddress(provinceRegion.getName()+cityRegion.getName()+districtRegion.getName()+" "+address);
        this.save(userAddress);

    }
}
